<?php

namespace App\Api\Sms;

use Illuminate\Support\Facades\Http;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;

class Danmi extends Base
{
    public $model = null;
    private $root;
    private $respDataType = "JSON";
    private $accountSid = null;
    private $apiUrl = null;
    private $apiToken = null;
    private $accountId = null;
//    验证码通知和营销不一样。
    private $accountId2 = null;
    private $timestamp = null;
    private $sendSignName = null;
    //    短信类型,与https://sms.danmi.com/index.html?time=20231122中的短信类型对应
    private $config = [
        'account_sid' => 'f08f102d9856f81d3d15fdcfc3ad6602',
        'token' => '361aa02ccfed38b5cfd324d68394e1aa',
        'sign_name' => '乔乔通信',
        'account_id2' => '1009573',
        'account_id' => '1009571'
    ];

    public function __construct()
    {
//        用配置数据吧
        $row = $this->config;
        $this->accountSid = $row['account_sid'] ?? null;
        $this->apiUrl = $row['api_url'] ?? null;
        $this->apiToken = $row['token'] ?? null;
        $this->accountId = $row['account_id'] ?? null;
        $this->accountId2 = $row['account_id2'] ?? null;
        $this->sendSignName = str_replace(['【', '】'], '', $row['sign_name']);

        list($msec, $sec) = explode(' ', microtime());
        $timestamp = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        $this->timestamp = $timestamp;
        $this->root = new Logger('DanmiSmsLog');
        $this->root->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/DanmiSmsLog.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
    }

//推送结果要签名验证数据
    public function sign($timestamp = null)
    {
        if (empty($timestamp)) {
            $timestamp = $this->timestamp;
        }
        return md5($this->accountSid . $this->apiToken . $timestamp);
    }

    public function getSign($data = [])
    {
        return $this->sign($data['timestamp']);
    }

//通过已经审核好的模板发送，成功率高，速度快
    public function sendSmsByTpl($phone, $tplId, $tplType = 3, $tplContent, $tplParamsData = [])
    {
//        $tplId = $tplRowData['tpl_id'] ?? '';
//        分析变量
        $tplParams = $this->parseTplParams($tplContent, $tplParamsData);

        $apiUrl = 'https://openapi.danmi.com/distributor/sendSMS';
        if (empty($phone)) {
            return $this->returnMsg(1, '发送的手机号不能为空');
        }
        if (empty($tplId)) {
            return $this->returnMsg(2, '请正确填写已经审核通过的模板');
        }
        if (is_array($phone)) {
            $phone = implode(',', $phone);
        }
        if (is_array($tplParams) && !empty($tplParams)) {
            $tplParams = implode(',', $tplParams);
        }
        $postData = [
            "respDataType" => $this->respDataType,
            "accountSid" => $this->accountSid,
//            发送手机号，多个手机号，用英文逗号隔开
            "to" => is_array($phone) ? implode(",", $phone) : $phone,
            "templateid" => $tplId,
            "param" => $tplParams,
            "timestamp" => $this->timestamp,
            "sig" => $this->sign(),
        ];
//        print_r($postData);

        $res = $this->requestSms($apiUrl, $postData);
//        return $this->returnMsg(15, 'f发送', $res);
//        print_r($res);
        if (intval($res['respCode']) === 0) {
            return ['code' => 200, 'msg' => '发送成功', 'data' => $res];
        }
        return ['code' => -1, 'msg' => $res['respDesc']];
    }

//发送短信,通过内容发送，这个可能会收不到，内容都要审核
    public function sendSms($phone, $content)
    {
        $apiUrl = 'https://openapi.danmi.com/distributor/sendSMS';
        if (empty($content)) {
            return $this->returnMsg(103, '发送的内容不能为空');
        }
        if (empty($phone)) {
            return $this->returnMsg(103, '发送的手机号不能为空');
        }
        $content = preg_replace("/【.+?】/", '', $content);
        $content = "【" . $this->sendSignName . "】" . $content;
        $postData = [
            "respDataType" => $this->respDataType,
            "accountSid" => $this->accountSid,
//            发送手机号，多个手机号，用英文逗号隔开
            "to" => is_array($phone) ? implode(",", $phone) : $phone,
            "smsContent" => $content,
            "timestamp" => $this->timestamp,
            "sig" => $this->sign(),
        ];
//        print_r($postData);
        $res = $this->requestSms($apiUrl, $postData);
//        print_r($res);
        if (intval($res['respCode']) === 0) {
            return ['code' => 200, 'msg' => '发送成功', 'data' => $res];
        }
        return ['code' => -1, 'msg' => $res['respDesc']];
    }


//创建短信模版
    public function addTpl($tplName, $tplType, $tplContent)
    {
        if (empty($tplName) || empty($tplContent)) {
            return ['code' => -1, 'msg' => '模版内容缺少必要内容'];
        }
//        模板内容，营销短信，请带 退订回T（加上短信签名，不超过350个字符）
        $tplContent = preg_replace("/【.+?】/", '', $tplContent);
//        $tplContent = "【" . $this->sendSignName . "】" . $tplContent;
        $accountId = $this->accountId;
        if ($tplType == 3) {
//            短信模板类型 1、验证码，2、通知，3、营销
            $tplContent = $tplContent . "退订回T";
            $accountId = $this->accountId2;
        }
        $apiUrl = 'https://openapi.danmi.com/distributor/smsTemplate/create';
        $postData = [
            "respDataType" => $this->respDataType,
            "accountSid" => $this->accountSid,
            "timestamp" => $this->timestamp,
            "sig" => $this->sign(),
            "accountId" => $accountId,
            //            后台配置的数据与接口端同步
            "templateName" => $tplName ?? null,
            "templateContent" => $tplContent ?? null,
            "templateType" => $tplType ?? 1,
            "templateSign" => "【" . $this->sendSignName . "】"
        ];
        $res = $this->requestSms($apiUrl, $postData);
//        print_r($res);
        if (intval($res['respCode']) === 0) {
            $data = [
                'templateId' => $res['templateid']
            ];
            return ['code' => 200, 'msg' => '创建模版成功', 'data' => $data];
        }
        return ['code' => -1, 'msg' => '创建模版失败'];
    }

//    修改模版内容
    public function editTpl($tplId, $tplName, $tplContent)
    {
        $apiUrl = 'https://openapi.danmi.com/distributor/smsTemplate/update';
        $postData = [
            "respDataType" => $this->respDataType,
            "accountSid" => $this->accountSid,
            "timestamp" => $this->timestamp,
            "sig" => $this->sign(),
            "accountId" => $this->accountId,
            //            后台配置的数据与接口端同步
            "templateName" => $tplName ?? null,
            "templateContent" => $tplContent ?? null,
            "templateid" => $tplId ?? 0,
            "templateSign" => "【" . $this->sendSignName . "】"
        ];
        $res = $this->requestSms($apiUrl, $postData);
//        print_r($res);
        if (intval($res['respCode']) === 0) {
            return ['code' => 200, 'msg' => '修改模版成功', 'data' => $res];
        }
        return ['code' => -1, 'msg' => $res['respDesc']];
    }

//    删除模版
    public function delTpl($tpl_id)
    {
        $apiUrl = 'https://openapi.danmi.com/distributor/smsTemplate/delete';
        $postData = [
            "respDataType" => $this->respDataType,
            "accountSid" => $this->accountSid,
            "timestamp" => $this->timestamp,
            "sig" => $this->sign(),
//            "accountId" => $this->accountId,
            //            后台配置的数据与接口端同步
            "templateid" => $tpl_id,
        ];
        $res = $this->requestSms($apiUrl, $postData);
//        print_r($res);
        if (intval($res['respCode']) === 0) {
            return ['code' => 200, 'msg' => '删除模版成功', 'data' => $res];
        }
        return ['code' => -1, 'msg' => '删除模版失败'];
    }

//短信查询模板
    public function queryTpl($tpl_id)
    {
        $apiUrl = 'https://openapi.danmi.com/distributor/smsTemplate/query';
        $postData = [
            "respDataType" => $this->respDataType,
            "accountSid" => $this->accountSid,
            "timestamp" => $this->timestamp,
            "sig" => $this->sign(),
//            "accountId" => $this->accountId,
            //            后台配置的数据与接口端同步
            "templateid" => $tpl_id,
        ];
        $res = $this->requestSms($apiUrl, $postData);
//        print_r($res);
        if (intval($res['respCode']) === 0) {
            return ['code' => 200, 'msg' => '查询模版成功', 'data' => $res];
        }
        return ['code' => -1, 'msg' => '查询模版失败'];
    }

//    短信余额查询
    public function getBalance()
    {
        $apiUrl = 'https://openapi.danmi.com/distributor/user/query';
        $postData = [
            "respDataType" => $this->respDataType,
            "accountSid" => $this->accountSid,
            "timestamp" => $this->timestamp,
            "sig" => $this->sign(),
            "accountId" => $this->accountId,
        ];
        $res = $this->requestSms($apiUrl, $postData);
//        print_r($res);
        if (intval($res['respCode']) === 0) {
            return ['code' => 200, 'msg' => '修改模版成功', 'data' => $res];
        }
        return ['code' => -1, 'msg' => $res['respDesc']];
    }

    public function requestSms($apiUrl, $data)
    {
        $response = Http::withOptions([
//            'debug' => true,
            'timeout' => 30,
            'connect_timeout' => 30,
            'read_timeout' => 30
        ])->asForm()->timeout(30)->post($apiUrl, $data);
        return $response->json();

//        $curl = curl_init(); // 启动一个CURL会话
//        curl_setopt($curl, CURLOPT_URL, $apiUrl); // 要访问的地址
//        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
//        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
//        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
//        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); // 使用自动跳转
//        curl_setopt($curl, CURLOPT_AUTOREFERER, true); // 自动设置Referer
//        curl_setopt($curl, CURLOPT_POST, true); // 发送一个常规的Post请求
//        curl_setopt($curl, CURLOPT_POSTFIELDS, is_array($data) ? http_build_query($data) : $data); // Post提交的数据包
//        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
//        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30); // 设置超时限制防止死循环
//        curl_setopt($curl, CURLOPT_HEADER, false); // 显示返回的Header区域内容
//        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
//        $res = curl_exec($curl); // 执行操作
//        if (curl_errno($curl)) {
//            //捕抓异常
//            return ['status' => -1, 'msg' => curl_error($curl)];
//        }
//        curl_close($curl); // 关闭CURL会话
//        return json_decode($res, true);
    }

    public function returnMsg($code = 200, $msg = '', $data = [])
    {
        return [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];
    }
}
